package com.tedu.controller;

import com.tedu.show.GameConstants;

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.FloatControl;
import java.net.URL;

/**
 * 音乐播放器
 * <p>负责加载和播放背景音乐
 */
public class MusicPlayer {
    private Clip currentClip;
    private String currentTrackPath;    // 当前播放的音乐路径
    private FloatControl volumeControl; // 音量控制器

    public MusicPlayer() {}

    /**
     * 播放或切换音乐。
     * @param filePath 音频文件的相对路径
     * @param loop 是否循环播放
     */
    public void playMusic(String filePath, boolean loop) {
        // 音乐已经在播放
        if (filePath.equals(currentTrackPath) && currentClip != null && currentClip.isRunning()) {
            return;
        }
        //  停止当前正在播放的音乐
        stopMusic();

        try {
            currentTrackPath = filePath;
            URL musicUrl = getClass().getClassLoader().getResource(filePath);

            if (musicUrl == null) {
                System.err.println("找不到音频文件: " + filePath);
                return;
            }

            AudioInputStream audioStream = AudioSystem.getAudioInputStream(musicUrl);
            currentClip = AudioSystem.getClip();
            currentClip.open(audioStream);

            // 获取音量控制器
            if (currentClip.isControlSupported(FloatControl.Type.MASTER_GAIN)) {
                this.volumeControl = (FloatControl) currentClip.getControl(FloatControl.Type.MASTER_GAIN);
            }

            if (loop) {
                currentClip.loop(Clip.LOOP_CONTINUOUSLY);
            } else {
                currentClip.start();
            }
        } catch (Exception e) {
            System.err.println("播放音频时出错: " + filePath);
            throw new RuntimeException(e);
        }
    }

    /**
     * 设置音量
     * @param volume 0.0 (静音) 到 1.0 (最大音量) 之间的浮点数
     */
    public void setVolume(float volume) {
        if (volumeControl != null) {
            try {
                // 将音量值转换为分贝
                float dB = (float) (Math.log(volume) / Math.log(10.0) * 20.0);
                volumeControl.setValue(dB);
            } catch (Exception e) {
                System.err.println("设置音量出错。");
                throw new RuntimeException();
            }
        }
    }

    /**
     * 停止当前音乐
     */
    public void stopMusic() {
        if (currentClip != null) {
            currentClip.stop();
            currentClip.close();
            currentClip = null;
            currentTrackPath = null;
        }
    }
}
